package com.ruoyi.iot.exchange.network.tcp.handler.impl;


import com.ruoyi.iot.domain.IotFrame;
import com.ruoyi.iot.exchange.network.tcp.cache.TcpChannelCache;
import com.ruoyi.iot.exchange.network.tcp.handler.dispatch.TCPDispatchHandler;
import com.zxq.factory.decoder.FiledDecoderFactory;
import com.zxq.factory.enums.EField;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.impl.util.HexBin;

@Slf4j
public class HexHeartSkipDispatchHandler extends TCPDispatchHandler {

    /**
     * 心跳数据描述
     */
    public HexHeartSkipDispatchHandler(IotFrame iotFrame) {
        super(iotFrame);
    }


    @Override
    public void decodeFrame() {
        byte[] frame = trimFrame();
        if(frame == null) {
            log.info("frame is empty");
            return;
        }
        String devCode =  TcpChannelCache.getDevId(channel);

        if(StringUtils.isEmpty(devCode)){
            log.info(String.format("illegal device up heartSkip",in.toString()));
        } else {
            String info = inflateInfo(frame);
            log.info(String.format("devCode:%s heart data:%s", devCode, info));
        }

        log.info("type: " + getClass().getSimpleName() + " frame:" + HexBin.bytesToString(frame));
    }

    @Override
    protected byte[] patternHex(byte[] frame) {

        return frame;
    }


    @Override
    protected String takeDevId(byte[] frame) {

        return null;
    }





    @Override
    protected Integer getDataLen(byte[] dataLenBuff) {
        return  (Integer) FiledDecoderFactory.instance().create(EField.Int).decoder(dataLenBuff);
    }

    protected String inflateInfo(byte[] frame) {

        Integer dataType = iotFrame.getFieldType().intValue();
        String heartMsg = FiledDecoderFactory.instance().create(EField.getType(dataType)).decoder(frame) + "";

        return heartMsg;
    }


}
